package com.fruit.service.promotion.impl;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.fruit.mapper.promotion.ActivityMapper;
import com.fruit.pojo.promotion.ActivityException;
import com.fruit.util.DateUtil;

import lombok.extern.slf4j.Slf4j;


/**
 * 
 * 活动日志类
 *
 * @author shibeilei
 * @version 2017.12.01 11:10
 *
 */
@Slf4j
@Service
public class ActivityLogService {
	
	@Autowired
	private ActivityMapper activityMapper;
	
	/**
	 * 插入活动日志
	 * @param tradeId tradeId
	 * @param serviceName serviceName
	 * @param serviceState serviceState
	 * @param activityId activityId
	 * @param userId userId
	 * @param params params
	 * @param code code
	 * @param message message
	 */
	public void newSaveExceptionActivity(String tradeId, String serviceName, String serviceState, long transId,
			int activityId, int userId, BigDecimal amount, String code, String message) {
		try {
			log.info("[{}]-【活动异常日志】-【活动Id：{}】", tradeId, activityId);
			ActivityException ae = new ActivityException();
			ae.setTradeId(tradeId);
			ae.setServiceName(serviceName);
			ae.setActivityId(activityId);
			ae.setUserId(userId);
			JSONObject paJson = new JSONObject();
			paJson.put("transId", transId);
			paJson.put("activityId", activityId);
			paJson.put("userId", userId);
			paJson.put("amount", amount);
			ae.setInputParams(paJson.toString());
			ae.setServiceState(serviceState);
			ae.setErrorCode(code);
			ae.setErrorMessage(message);
			ae.setQueryTime(DateUtil.getTime());
			activityMapper.saveExceptionActivity(ae);
			log.info("[{}]-【活动异常日志】-【成功】", tradeId);
		} catch (Exception e) {
			log.error("[{}]-【活动异常日志】-【异常】------【{}】", tradeId, getStackTraceAsString(e));
		}
		log.info("[{}]-【活动异常日志】-【结束】", tradeId);

	}


	/**
	 * 打印异常信息
	 * @param ex ex
	 * @return 返回异常信息
	 * @author shibeilei
	 * @version 2017.12.01 11:10
	 */
	public String getStackTraceAsString(Throwable ex) {
		StringWriter stringWriter = new StringWriter();
		ex.printStackTrace(new PrintWriter(stringWriter));
		return stringWriter.toString();
	}

}
